import React, { useState } from "react";
import { NavLink, useNavigate } from 'react-router-dom';
import { connect } from 'react-redux'

import './index.css'
import api from "../../api";
import cookie from "react-cookies";
import { createLogin, createLogout } from "../../redux/actions/login";

function Login(props) {

    const [account, setAccount] = useState("") //这是账户数据
    const [pwd, setPwd] = useState("") //这是密码数据
    const navigate = useNavigate()

    //处理登录
    async function handleLogin(e) {
        e.preventDefault()
        let data = await api.loginApi({
            account,
            password: pwd,
        }) //data为返回的数据
        if (data.status === 200) {
            cookie.save('user-token', data.data)  //data里的data字段用于区分每一位用户
            console.log('登录成功,id为:', data.data)
            let info = await api.getUserInfoApi()
            if (info.status === 200) {
                console.log('获取登录信息成功拉')
                props.login(true)
                navigate('/home', { replace: true })
            } else {
                console.log('获取登录信息失败', data.message)
            }
        } else {
            console.log('登录失败', data.message)   //请求失败，输出原因
        }
    }
    //用于更新账户和密码输入
    function update(e, func) {
        func(e.target.value)
    }

    return (
        <div className={'panel panel-default login'}>
            <div className={'panel-heading text-center'}>
                <div className={'head'}>账号登录</div>
            </div>
            <div className={'panel-body'}>
                <form action="#">
                    <div className={'form-group login'}>
                        <input type="text" className={'form-control login'} placeholder={'请输入邮箱'}
                            onChange={(e) => { update(e, setAccount) }}/>
                    </div>
                    <div className={'form-group login'}>
                        <input type={'password'} className={'form-control login'} placeholder={'请输入密码'}
                            onChange={(e) => { update(e, setPwd) }}/>
                    </div>
                    <div className={'checkbox'}>
                        <label><input type="checkbox"/>登录即代表同意协议</label>
                    </div>
                    <button type={'submit'} className={'btn btn-default login'} onClick={handleLogin}>登录</button>
                </form>
                <NavLink to={'/register'}>注册账号</NavLink>
                <NavLink to={'/forgetpwd'} style={{ textAlign: "right" }}>忘记密码？</NavLink>
            </div>
        </div>
    )
}

//创建容器组件
//向ui组件传递状态对象
function mapStateToProps(state) {
    return {
        loginState: state.loginState
    }
}
//向ui组件传递操作状态对象的方法
function mapDispatchToProps(dispatch) {
    return {
        login: (data) => { dispatch(createLogin(data)) },
        logout: (data) => { dispatch(createLogout(data)) }
    }
}
//连接容器组件与ui组件
const LoginContainer = connect(mapStateToProps, mapDispatchToProps)(Login)
export default LoginContainer